package service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import net.sf.ezmorph.bean.MorphDynaBean;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.ddlutils.DatabaseOperationException;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.model.Table;

import static utils.DBHelper.getData;
import utils.JsonHelper;

public class DataQueryImpl implements IDataQuery {

	@Override
	public void getDataFromTemplateJson(String json) {
		DynaBean bean = JsonHelper.getDynaBeanFromJson(json);


		DynaBean tableBean = (DynaBean)bean.get("TableDefine");

		getBeanTable(tableBean);
	}

	private void getBeanTable(DynaBean tableBean){
		String tableName = (String) tableBean.get("TableName");
		getData(tableName, "");

		boolean isNextTable = false;
		DynaProperty[] props = tableBean.getDynaClass().getDynaProperties();
		for (DynaProperty dynaProperty : props) {
			String name = dynaProperty.getName();
			if("FieldList".equalsIgnoreCase(name)){
				isNextTable = true;
				break;
			}
		}

		if(!isNextTable) return;

		Collection<MorphDynaBean> fieldList = (Collection<MorphDynaBean>) tableBean.get("FieldList");
		for (MorphDynaBean morphDynaBean : fieldList) {
			String type = (String)morphDynaBean.get("type");
			if(type.equals("table")){
				DynaBean nextTablebean = (MorphDynaBean)morphDynaBean.get("refTable");
				getBeanTable(nextTablebean);
			}
		}
	}


	public void getDataFromTable(String tableName, String id) {
		getData(tableName, id);
	}


	public void getDataFromBean(DynaBean bean) {
		DynaBean tableBean = (DynaBean) bean.get("TableDefine");
		String tableName = (String) tableBean.get("TableName");
		System.out.println("getData from table:" + tableName);
		getDataFromTable(tableName,"");
	}

}
